package com.example.chenz.alarmservice;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

import java.sql.Ref;
import java.util.Calendar;


public class MainActivity extends AppCompatActivity implements OnClickListener {

    private static MainActivity appRef = null;
    private Button call_alarm_service;
    private Button exit_alarm_service;
    boolean flag = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        appRef = this;
        setContentView(R.layout.activity_main);

        call_alarm_service = (Button)findViewById(R.id.button1);
        call_alarm_service.setOnClickListener(this);
        exit_alarm_service = (Button)findViewById(R.id.button2);
        exit_alarm_service.setOnClickListener(this);
    }
    public static MainActivity getApp() {return appRef;}

    public void btEvent(String data) {setTitle(data);}

    public void onClick(View view){
        if (view == call_alarm_service) {
            setTitle("进入倒计时：5");
            Intent intent = new Intent(MainActivity.this,AlarmReceiver.class);
            PendingIntent pendingIntent = PendingIntent.getBroadcast(MainActivity.this,0,intent,0);
            Calendar calendar = Calendar.getInstance();
            calendar.setTimeInMillis(System.currentTimeMillis());
            calendar.add(Calendar.SECOND,5);

            AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
            alarmManager.set(AlarmManager.RTC_WAKEUP,calendar.getTimeInMillis(),pendingIntent);
        }

        if (view == exit_alarm_service) {
            Intent intent = new Intent(MainActivity.this,AlarmReceiver.class);
            PendingIntent pendingIntent = PendingIntent.getBroadcast(MainActivity.this,0,intent,0);
            AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
            alarmManager.cancel(pendingIntent);

            finish();
        }
    }

}
